package com.yanxi.yxregiserve.web.scheduled;

import com.yanxi.yxregiserve.web.common.util.ManagedChannelUtils;
import com.yanxi.yxregiserve.web.domin.system.ClientExample;
import com.yanxi.yxregiserve.web.grpc.RegisterService.HealthRequest;
import com.yanxi.yxregiserve.web.grpc.RegisterService.HealthResponse;
import com.yanxi.yxregiserve.web.grpc.RegisterService.RegisterServiceGrpc;
import com.yanxi.yxregiserve.web.service.system.ClientExampleService;
import io.grpc.ManagedChannel;
import io.grpc.health.v1.HealthGrpc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

@Component
public class HealthcheckTask {

    @Autowired
    private ClientExampleService clientExampleService;

    private static final Logger logger = Logger.getLogger(HealthcheckTask.class.getName());

    /**
     * 定时任务 - 心跳检测 60秒检测一次
     */
    @Scheduled(cron = "0/60 * * * * ?")
    public void heartbeatCheck() {

        logger.info("Heartbeat detection begins ₍ᐢ..ᐢ₎♡");

        /**
         * 查询 serType = 0 和 1 （健康和异常的 除了死亡的） 实例List
         */
        List<ClientExample> clientExamples = clientExampleService.selectTList(ClientExample.builder().serType("0").build());
        List<ClientExample> clientExamples1 = clientExampleService.selectTList(ClientExample.builder().serType("1").build());
        clientExamples.addAll(clientExamples1);

        for (ClientExample clientExample : clientExamples) {

            ManagedChannelUtils.runWithManagedChannel(clientExample.getInNetIp(), clientExample.getPort(), channel -> {

                RegisterServiceGrpc.RegisterServiceBlockingStub registerServiceBlockingStub = RegisterServiceGrpc.newBlockingStub(channel);
                HealthResponse healthcheck = registerServiceBlockingStub.healthcheck(HealthRequest.newBuilder().build());

                if (200 == healthcheck.getStatus()) {

                    /**
                     * 检测次数 + 1
                     * checkNum + 1
                     */
                    clientExample.setCheckNum(clientExample.getCheckNum() + 1);
                    clientExampleService.updateT(clientExample);

                    logger.info(clientExample.getProjectName() + " success ₍ᐢ..ᐢ₎♡");

                } else {
                    /**
                     * 检测十次 都是异常 才判定死亡
                     */
                    if (clientExample.getExceNum() > 10) {

                        logger.info(clientExample.getProjectName() + " death (っ◞‸◟c)");

                        /**
                         * 修改这条数据为死亡
                         * serType = 2
                         */
                        clientExample.setSerType("2");
                        clientExample.setDeathTime(new Date());
                        clientExampleService.updateT(clientExample);
                    } else {

                        logger.info(clientExample.getProjectName() + " exceptional (っ◞‸◟c)");

                        /**
                         * 修改这条数据为异常,然后检测次数 + 1,异常次数 + 1 异常时间[现在时间字符串拼接在原有数据之后]
                         * serType = 1;checkNum + 1;exceNum + 1;
                         */
                        clientExample.setCheckNum(clientExample.getCheckNum() + 1);
                        clientExample.setExceNum(clientExample.getExceNum() + 1);
                        clientExample.setExceptTime(clientExample.getExceptTime() + "," + new Date().toString());
                        clientExampleService.updateT(clientExample);
                    }
                }
            });
        }
    }
}
